<template>
  <div>
    <teacher-menu></teacher-menu>
    <main class="ml-64 flex-1 p-6 bg-gray-50 min-h-screen">
      <h2>学生答卷列表</h2>

      <el-table :data="answers" style="width: 100%" @row-dblclick="viewAnswer">
        <el-table-column prop="id" label="回答ID" width="80" />
        <el-table-column prop="examid" label="试卷ID" width="100" />
        <el-table-column prop="yhm" label="学生学号" />
        <el-table-column prop="submittedat" label="提交时间" />
      </el-table>

      <el-dialog :visible.sync="dialogVisible" width="700px" :before-close="closeDialog" title="答卷详情">
        <div v-if="detailedAnswer">
          <h3>{{ detailedAnswer.title }}</h3>
          <p><em>描述：{{ detailedAnswer.description }}</em></p>
          <el-divider></el-divider>

          <div v-for="(q, idx) in detailedAnswer.questions" :key="idx" style="margin-bottom: 20px">
            <p><strong>题 {{ idx + 1 }}：</strong>{{ q.title }}</p>
            <div>
              <template v-if="q.type === 'text'">
                <el-input type="textarea" :value="getAnswer(q, idx)" disabled />
              </template>

              <template v-else-if="q.type === 'single'">
                <el-radio-group v-model="detailedAnswer.answers[idx]" disabled>
                  <el-radio v-for="(opt, i) in q.options" :key="i" :label="opt.content">
                    {{ opt.content }}
                  </el-radio>
                </el-radio-group>
              </template>

              <template v-else-if="q.type === 'multiple'">
                <el-checkbox-group v-model="detailedAnswer.answers[idx]" disabled>
                  <el-checkbox v-for="(opt, i) in q.options" :key="i" :label="opt.content">{{ opt.content }}</el-checkbox>
                </el-checkbox-group>
              </template>
            </div>
          </div>
        </div>
        <div v-else>
          <p>加载中...</p>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </main>
  </div>
</template>

<script>
import TeacherMenu from "@/components/teacher/Teacher_menu.vue";
import axios from "axios";
import {EventBus} from "@/event-bus";

export default {
  name: "TeacherDcwjAnswer",
  components: { TeacherMenu },
  data() {
    return {
      UserInfo: {
        id: '',
        name: '',
        role: '',
        username: '',
      },
      answers: [], // 答卷列表
      dialogVisible: false,
      detailedAnswer: null, // 选中答卷及题目+答案
    };
  },
  mounted() {
    this.getLoginUserInfo();
  },
  methods: {
    async loadAnswers() {
      try {
        const res = await axios.get(`/dcwjk/getDcwjkAnswerList2?yhm=`+this.UserInfo.username); // 获取答卷列表
        this.answers = res.data.data;
      } catch (err) {
        this.$message.error("加载答卷失败");
        console.error(err);
      }
    },
    getLoginUserInfo() {
      axios.get('/user/checkSession').then(response => {
        if (!response.data.result) {
          EventBus.$emit('show-auth-popup');
          setTimeout(() => {
            this.$router.push({name: 'TeacherLoginView'});
          }, 1000);
        } else {
          this.UserInfo.name = response.data.name;
          this.UserInfo.role = response.data.role;
          this.UserInfo.username = response.data.username;
          this.loadAnswers();
        }

      }).catch(error => {
        EventBus.$emit('show-auth-popup');
        console.error('获取用户信息失败,网络错误！', error);
        setTimeout(() => {
          this.$router.push({name: 'Login'});
        }, 1000);
      });
    },
    async viewAnswer(row) {
      this.dialogVisible = true;
      this.detailedAnswer = null;

      try {
        // 1. 根据答卷ID获取答卷详情
        const answerRes = await axios.get(`/dcwjk/getDcwjkAnswer?dcwjid=${row.id}`);

        // 2. 根据答卷中的 examid 获取试卷题目
        const paperRes = await axios.get(`/dcwjk/getDcwjk?dcwjid=${answerRes.data.data.examid}`);
        console.log("试卷：")
        console.log(paperRes.data);

        // 3. 解析题目列表和答案
        let questions = JSON.parse(paperRes.data.data.questions);
        console.log("问题：")
        console.log(questions);
        let answers = {};
        try {
          answers = JSON.parse(answerRes.data.data.answers);
          console.log("答案：")
          console.log(answers);
        } catch {
          answers = {};
        }

        // 4. 组装展示数据
        this.detailedAnswer = {
          title: paperRes.data.data.title,
          description: paperRes.data.data.description,
          questions: questions,
          answers: answers,
        };
        console.log("展示数据：")
        console.log(this.detailedAnswer);
      } catch (err) {
        this.$message.error("加载答卷详情失败");
        console.error(err);
      }
    },
    // 根据题目和索引获取对应答案
    getAnswer(q, idx) {
      if (!this.detailedAnswer || !this.detailedAnswer.answers) return "";
      const answers = this.detailedAnswer.answers;
      return answers[idx] || (q.type === "multiple" ? [] : "");
    },
    closeDialog() {
      this.dialogVisible = false;
      this.detailedAnswer = null;
    },
  },
};
</script>

<style scoped>
.el-dialog__body {
  max-height: 600px;
  overflow-y: auto;
}
</style>
